package com.zenithmind.exam.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.common.exception.BusinessException;
import com.zenithmind.exam.mapper.QuestionFavoriteMapper;
import com.zenithmind.exam.pojo.entity.QuestionFavorite;
import com.zenithmind.exam.pojo.vo.QuestionVO;
import com.zenithmind.exam.service.QuestionFavoriteService;
import com.zenithmind.exam.service.QuestionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 题目收藏服务实现类
 * 
 * @author ZenithMind
 * @since 2024-07-01
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class QuestionFavoriteServiceImpl extends ServiceImpl<QuestionFavoriteMapper, QuestionFavorite> implements QuestionFavoriteService {

    private final QuestionFavoriteMapper questionFavoriteMapper;
    private final QuestionService questionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean favoriteQuestion(String userId, String questionId) {
        try {
            // 检查是否已经收藏
            if (isFavorited(userId, questionId)) {
                throw new BusinessException("题目已经收藏过了");
            }

            QuestionFavorite favorite = new QuestionFavorite();
            favorite.setUserId(userId);
            favorite.setQuestionId(questionId);
            favorite.setCreateTime(LocalDateTime.now());

            boolean result = save(favorite);
            if (result) {
                log.info("收藏题目成功，用户ID: {}, 题目ID: {}", userId, questionId);
            }
            return result;
        } catch (Exception e) {
            log.error("收藏题目失败", e);
            throw new BusinessException("收藏题目失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean unfavoriteQuestion(String userId, String questionId) {
        try {
            int result = questionFavoriteMapper.deleteByUserIdAndQuestionId(userId, questionId);
            if (result > 0) {
                log.info("取消收藏题目成功，用户ID: {}, 题目ID: {}", userId, questionId);
            }
            return result > 0;
        } catch (Exception e) {
            log.error("取消收藏题目失败", e);
            throw new BusinessException("取消收藏题目失败: " + e.getMessage());
        }
    }

    @Override
    public boolean isFavorited(String userId, String questionId) {
        return questionFavoriteMapper.isFavorited(userId, questionId);
    }

    @Override
    public List<QuestionVO> getUserFavoriteQuestions(String userId) {
        List<String> questionIds = questionFavoriteMapper.selectQuestionIdsByUserId(userId);
        return questionIds.stream()
                .map(questionId -> questionService.getQuestionById(questionId, false))
                .filter(question -> question != null)
                .collect(Collectors.toList());
    }

    @Override
    public IPage<QuestionVO> getUserFavoriteQuestionPage(Page<QuestionFavorite> page, String userId) {
        IPage<QuestionFavorite> favoritePage = questionFavoriteMapper.selectFavoritePageByUserId(page, userId);
        
        IPage<QuestionVO> voPage = new Page<>();
        voPage.setCurrent(favoritePage.getCurrent());
        voPage.setSize(favoritePage.getSize());
        voPage.setTotal(favoritePage.getTotal());
        voPage.setPages(favoritePage.getPages());
        
        List<QuestionVO> voList = favoritePage.getRecords().stream()
                .map(favorite -> questionService.getQuestionById(favorite.getQuestionId(), false))
                .filter(question -> question != null)
                .collect(Collectors.toList());
        voPage.setRecords(voList);
        
        return voPage;
    }

    @Override
    public Integer countUserFavorites(String userId) {
        return questionFavoriteMapper.countByUserId(userId);
    }

    @Override
    public Integer countQuestionFavorites(String questionId) {
        return questionFavoriteMapper.countByQuestionId(questionId);
    }

    @Override
    public List<QuestionVO> getMostFavoritedQuestions(Integer limit) {
        List<QuestionFavorite> favorites = questionFavoriteMapper.selectMostFavoritedQuestions(limit);
        return favorites.stream()
                .map(favorite -> questionService.getQuestionById(favorite.getQuestionId(), false))
                .filter(question -> question != null)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean clearUserFavorites(String userId) {
        try {
            int result = questionFavoriteMapper.deleteByUserId(userId);
            if (result > 0) {
                log.info("清空用户收藏成功，用户ID: {}, 清空数量: {}", userId, result);
            }
            return result > 0;
        } catch (Exception e) {
            log.error("清空用户收藏失败", e);
            throw new BusinessException("清空用户收藏失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchFavoriteQuestions(String userId, List<String> questionIds) {
        try {
            int successCount = 0;
            for (String questionId : questionIds) {
                if (!isFavorited(userId, questionId)) {
                    QuestionFavorite favorite = new QuestionFavorite();
                    favorite.setUserId(userId);
                    favorite.setQuestionId(questionId);
                    favorite.setCreateTime(LocalDateTime.now());
                    
                    if (save(favorite)) {
                        successCount++;
                    }
                }
            }
            
            log.info("批量收藏题目完成，用户ID: {}, 成功数量: {}/{}", userId, successCount, questionIds.size());
            return successCount > 0;
        } catch (Exception e) {
            log.error("批量收藏题目失败", e);
            throw new BusinessException("批量收藏题目失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchUnfavoriteQuestions(String userId, List<String> questionIds) {
        try {
            int successCount = 0;
            for (String questionId : questionIds) {
                int result = questionFavoriteMapper.deleteByUserIdAndQuestionId(userId, questionId);
                if (result > 0) {
                    successCount++;
                }
            }
            
            log.info("批量取消收藏题目完成，用户ID: {}, 成功数量: {}/{}", userId, successCount, questionIds.size());
            return successCount > 0;
        } catch (Exception e) {
            log.error("批量取消收藏题目失败", e);
            throw new BusinessException("批量取消收藏题目失败: " + e.getMessage());
        }
    }

    @Override
    public List<String> getUserFavoriteQuestionIds(String userId) {
        return questionFavoriteMapper.selectQuestionIdsByUserId(userId);
    }
}
